package com.topscomm.cbo.controller;

import com.topscomm.basic.util.Config;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.controller.auto.CboApprovalNodeInsControllerAuto;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapApprovalNodeStateEnum;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("cbo/approvalNodeIns")
public class CboApprovalNodeInsController extends CboApprovalNodeInsControllerAuto
		implements ICboApprovalNodeInsController {
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_flowid")) {
			String value = paraMap.get("qry_flowid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and flowid = {0} ", value);
		}
		if (paraMap.containsKey("qry_flowinsid")) {
			String value = paraMap.get("qry_flowinsid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and flowinsid = {0} ", value);
		}
		if (paraMap.containsKey("qry_nodeid")) {
			String value = paraMap.get("qry_nodeid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and nodeid = {0} ", value);
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = {0} ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_startdate1")) {
			String value = paraMap.get("qry_startdate1").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and nodeins.startdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_startdate2")) {
			String value = paraMap.get("qry_startdate2").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and nodeins.startdate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_approvaluserid")) {
			String value = paraMap.get("qry_approvaluserid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvaluserid = {0} ", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and nodeins.state = {0} ", value);
		}
		if (paraMap.containsKey("qry_maintitle")) {
			String value = paraMap.get("qry_maintitle").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and maintitle like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_approvalopinion")) {
			String value = paraMap.get("qry_approvalopinion").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvalopinion like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_approvaldate1")) {
			String value = paraMap.get("qry_approvaldate1").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvaldate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_approvaldate2")) {
			String value = paraMap.get("qry_approvaldate2").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvaldate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_approvalOpinionIsNotNull")
				&& "true".equals(paraMap.get("qry_approvalOpinionIsNotNull").toString())) {
			sql.appendSingle(" and  not (approvalexplain='' or approvalexplain is null) ");
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0} ", value);
		}
		if (paraMap.containsKey("qry_approvalOpinion")
				&& !StringUtil.isEmpty(paraMap.get("qry_approvalOpinion").toString())) {
			sql.appendSingle(" and ApprovalOpinion like '%{0}%' ", paraMap.get("qry_approvalOpinion").toString());
		}
		if (paraMap.containsKey("qry_approvalUserId")
				&& !StringUtil.isEmpty(paraMap.get("qry_approvalUserId").toString())) {
			sql.appendSingle(" and ApprovalUserId = '{0}' ", paraMap.get("qry_approvalUserId").toString());
		}
		return sql.toString();
	}

	/**
	 * @description:待审批列表
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年3月19日下午6:30:05
	 * @modify:
	 */
	@GetMapping("/queryApprovalList1")
	public ResponseResult<Object> queryApprovalList(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		Object[] list = paraMap.keySet().toArray();
		for (Object entry : list) {
			if (ConvertUtil.convertToString(entry).startsWith("qry_")) {
				if (StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get(entry))))
					paraMap.remove(entry);
			}
		}
		String qry_list  = this.spellListSql(paraMap);
		paraMap.put("qry_approvaluserid", this.getUserBean().getUser().getId());
		if (!paraMap.containsKey("qry_state")) {
			paraMap.put("qry_state", 1);
		}
		// 待审批单据的来源系统在config.properties中配置 --李正亮 2019-1-8 add
		String approvalSourceSystem = Config.getInstance().getValue("ApprovalSourceSystem", "Top");
		String[] approvals = approvalSourceSystem.split(",");
		String qry_where = " and (";
		for (String approval : approvals) {
			qry_where = qry_where + " flowins.sourcetype like '" + approval + "%' or ";
		}
		qry_where = qry_where.substring(0, qry_where.length() - 3) + ")";
		qry_where = qry_where + " and " + qry_list;
		paraMap.put("qry_where", qry_where);
		int totalCount = service.getCount(paraMap, "myApprovalCount");
		List<Map<String, Object>> tempList = service.queryMapForPage(query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), paraMap, "myApprovalList");
		service.setDispFields(tempList);// fanzhiming 2018-09-12增加
		// 审批节点名称修改为从extendfield2字段取值，解决自循环竞争节点名称细化问题
		for (Map<String, Object> tempDataMap : tempList) {
			if (tempDataMap.get("extendfield2") != null
					&& !StringUtil.isEmpty(tempDataMap.get("extendfield2").toString())) {
				tempDataMap.put("dispnodeid", tempDataMap.get("extendfield2").toString());
			}
		}
		Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}



	/**
	 * @description: 查询待审批节点的信息
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年3月19日下午6:23:12
	 * @modify:
	 */
	@GetMapping("/queryNodeInfo")
	public ResponseResult<Object> queryNodeInfo(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		List<Map<String, Object>> list = this.service.queryMap(paraMap, "myApprovalOne");
		if (list != null && list.size() > 0) {
			// 处于审批中
			if (TapApprovalNodeStateEnum.Approveing == ConvertUtil.convertToInt(list.get(0).get("state"))) {
				return ResponseResult.ok(list.get(0));
			} else
				return ResponseResult.error("待办数据已经被处理！");
		} else
			return ResponseResult.error("没有找到对应的待审批数据！");
	}

	/**
	 * @description:用于审批人发生变化后，将正在进行的审批节点，审批人更换为新人
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2022年3月19日上午11:17:54
	 * @modify:
	 */
	@PostMapping(value = "/reBindApprovalUser")
	public ResponseResult<Object> reBindApprovalUser(@RequestBody Map<String, Object> paraMap) {
		try {
			long nodeId = ConvertUtil.convertToLong(paraMap.get("id"));
			service.reBindApprovalUser(nodeId);
			return ResponseResult.ok("操作成功");
		} catch (Exception e) {
			// TODO: handle exception
			return handleControllerException(e);
		}
	}


	/**
	 * @description:待审批列表中，各个审批类型数量查询
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年3月23日下午2:08:54
	 * @modify:
	 */
	@GetMapping("/querySouceTypeCount")
	public ResponseResult<Object> querySouceTypeCount(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 待审批单据的来源系统在config.properties中配置
		String approvalSourceSystem = Config.getInstance().getValue("ApprovalSourceSystem", "Top");
		String[] approvals = approvalSourceSystem.split(",");
		String qry_where = " and (";
		String qry_wherecode = " (";
		for (String approval : approvals) {
			qry_where = qry_where + " sourcetype like '" + approval + "%' or ";
			qry_wherecode = qry_wherecode + " code like '" + approval + "%' or ";
		}
		qry_where = qry_where.substring(0, qry_where.length() - 3) + ")";
		qry_wherecode = qry_wherecode.substring(0, qry_wherecode.length() - 3) + ")";
		List<Map<String, Object>> sourcetypeList = datacodeCache.getCodeListMap("CboApprovalFlowCategory", qry_wherecode, "sortcode");
		List<Map<String, Object>> resultList = service.selectExecute("select " + SQLAdapter.isNull("sourcetype", "'unknown'")
				+ " as code,count(1) as count from CboApprovalNodeins where state=1 and approvaluserid ='"
				+ this.getUserBean().getUser().getId() + "' and enabled=1 " + qry_where
				+ "group by sourcetype order by count desc");
		for (Map<String, Object> type : sourcetypeList) {
			boolean isHave = false;
			for (Map<String, Object> item : resultList) {
				if (type.get("code").toString().equals(item.get("code").toString())) {
					item.put("name", type.get("name"));
					isHave = true;
					break;
				}
			}
			if (!isHave) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", type.get("code"));
				map.put("name", type.get("name"));
				map.put("count", 0);
				resultList.add(map);
			}
		}
		return ResponseResult.ok(resultList);
	}

	/**
	 * @author
	 * @date 2019年9月6日
	 * @description 首页portal树形类别
	 * @return
	 */
	@GetMapping("/querySouceTypeTree")
	public ResponseResult<Object> querySouceTypeTree(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 待审批单据的来源系统在config.properties中配置
		String approvalSourceSystem = Config.getInstance().getValue("ApprovalSourceSystem", "Top");
		String[] approvals = approvalSourceSystem.split(",");
		String qry_where = " and (";
		for (String approval : approvals) {
			qry_where = qry_where + " sourcetype like '" + approval + "%' or ";
		}
		qry_where = qry_where.substring(0, qry_where.length() - 3) + ")";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> resultList = service.selectExecute("select " + SQLAdapter.isNull("sourcetype", "'unknown'")
				+ " as code,extendfield2 as name,count(1) as count from CboApprovalNodeins  where state=1 and approvaluserid ='"
				+ getUserBean().getUser().getId()
				+ "' and enabled=1 " + qry_where
				+ " group by sourcetype,extendfield2 having count(1)>0 order by sourcetype,count desc");
		List<Map<String, Object>> codeList = datacodeCache.getCodeListMap("CboApprovalFlowCategory", "", "sortcode");
		for (Map<String, Object> result : resultList) {
			Map<String, Object> parent = null;
			for (Map<String, Object> item : list) {
				if (item.containsKey("pcode") && result.get("code").toString().equals(item.get("pcode").toString())) {
					parent = item;
					break;
				}
			}
			if (parent == null) {
				parent = new HashMap<String, Object>();
				parent.put("code", result.get("code"));
				parent.put("pcode", result.get("code"));
				parent.put("name", result.get("code"));
				for (Map<String, Object> code : codeList) {
					if (result.get("code").toString().equals(code.get("code").toString())) {
						parent.put("name", code.get("name"));
						break;
					}
				}
				parent.put("count", result.get("count"));
				list.add(parent);
			} else {
				parent.put("count", Integer.parseInt(result.get("count").toString())
						+ Integer.parseInt(parent.get("count").toString()));
			}
			list.add(result);
		}
		return ResponseResult.ok(list);
	}
}
